//
//  LZPlayVideoManager.m
//  laziz_Consumer
//
//  Created by xbnzd on 16/12/6.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZPlayVideoManager.h"
#import "LZVideoTableViewCell.h"
#import "LZCustomPlayerView.h"
#import "LZVideoListModel.h"
#import "LZVideoPresenter.h"
#import "LZVideoCacheManager.h"
#import "LZVideoActivityView.h"
#import "Masonry.h"
#import "extobjc.h"

static CGFloat kRefreshSpace = 54.0f;//再计算cell在最上层vc中的位置时,由于MJRefresh的问题,有54的偏差.在这里标注,计算是进行纠正

@interface LZPlayVideoManager()
@property (nonatomic, strong) LZVideoActivityView *activityView;
@property (nonatomic, strong) UIButton *failedStateBtn;   //加载失败后展示

@property (nonatomic, strong) UIView *bgViewTemp;
@property (nonatomic, strong) LZCustomPlayerView *playerViewTemp;
@property (nonatomic, strong) NSString *videoIDTemp;
@property (nonatomic, strong) NSString *videoURLTemp;
@property (nonatomic, copy) void(^PlayCountBlock)(NSInteger countNum);
@end

@implementation LZPlayVideoManager

+ (instancetype)shareManager
{
    static LZPlayVideoManager *v = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        v = [[LZPlayVideoManager alloc] init];
    });
    
    return v;
}

#pragma mark - 滑动停止后播放视频计算方法
/**
 滑动停止后播放视频方法
 
 @param tableView tableview
 @param cellIndexPath 用来标记当前cell的indexpath
 @param playerView 播放View
 @return 返回当前正在播放的cell的indexpath
 */
- (NSIndexPath *)playVideoWhenTableViewStopScrollWithTableView:(UITableView *)tableView cellIndexPath:(NSIndexPath *)cellIndexPath playerView:(LZCustomPlayerView *)playerView playCountAddBlock:(void(^)(NSInteger totleCount))playCountBlock
{
    CGFloat screenMidY = SCREEN_HEIGHT/2; //屏幕中线
    NSArray *arr = [tableView indexPathsForVisibleRows];
    for (int i = 0; i < arr.count; i ++) {
        
        NSIndexPath *p = arr[i];
        CGRect cellRectInTable = [tableView rectForRowAtIndexPath:p];
        CGRect cellRectInSupeVCView = [tableView convertRect:cellRectInTable toView:nil];
        
        CGFloat playViewOriginY = cellRectInSupeVCView.origin.y - kRefreshSpace;
        CGFloat playViewLastY   = playViewOriginY + cellRectInSupeVCView.size.height;
        
        if (playViewOriginY < screenMidY && playViewLastY > screenMidY) {
            if (p.row == cellIndexPath.row) {
                if (cellIndexPath == nil) {
                    return [self playVideoWhenClickVideoCoverImgWithIndexPath:p playerView:playerView playCountAddBlock:playCountBlock];
                }else{
                    return cellIndexPath;
                }
            }
            return [self playVideoWhenClickVideoCoverImgWithIndexPath:p playerView:playerView playCountAddBlock:playCountBlock];
        }
    }
    
    return cellIndexPath;
}

#pragma mark - 滑动列表时,停止,并移除正在播放的视频
/**
 滑动列表时,停止,并移除正在播放的视频
 
 @param tableView tableview
 @param cellIndexPath 当前播放的cell的标记,用来查找相应的cell视图
 */
- (void)removePlayViewWhenTableViewDidScrollWithTableView:(UITableView *)tableView cellIndexPath:(NSIndexPath *)cellIndexPath
{
    CGFloat screenMidY = SCREEN_HEIGHT/2; //屏幕中线
    CGRect cellRectInTable = [tableView rectForRowAtIndexPath:cellIndexPath];
    CGRect cellRectInSupeVCView = [tableView convertRect:cellRectInTable toView:nil];
    CGFloat playViewOriginY = cellRectInSupeVCView.origin.y - kRefreshSpace;
    CGFloat playViewLastY   = playViewOriginY + cellRectInSupeVCView.size.height;
    
    if (playViewOriginY > screenMidY || playViewLastY < screenMidY) {
        LZVideoTableViewCell *cell = [tableView cellForRowAtIndexPath:cellIndexPath];
        for (id sub in cell.playerBgView.subviews) {
            if ([sub isKindOfClass:[LZCustomPlayerView class]]) {
                LZCustomPlayerView *v = (LZCustomPlayerView *)sub;
                [v stopAction];
                [v removeFromSuperview];
                
            }
        }
    }

}


#pragma mark - 某些详情页直接播放方法
#pragma mark -最终播放方法
/**
 某些详情页直接播放方法
 
 @param bgView 父视图
 @param playerView 播放View
 @param videoUrl 地址
 */
- (void)playVideoWithBgView:(UIView *)bgView playerView:(LZCustomPlayerView *)playerView videoURL:(NSString *)videoUrl videoID:(NSString *)videoId playCountAddBlock:(void(^)(NSInteger totleCount))playCountBlock
{
    self.bgViewTemp = bgView;
    self.playerViewTemp = playerView;
    self.videoIDTemp = videoId;
    self.videoURLTemp = videoUrl;
    self.PlayCountBlock = playCountBlock;
    
    NSURL *uu = [NSURL URLWithString:videoUrl];
    if (![videoUrl containsString:@"https"]) {
         uu = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,videoUrl]];
    }
    
//    NSURL *uu = [NSURL URLWithString:@"http://baobab.wdjcdn.com/14564977406580.mp4"];
    
    
    [self.activityView resetActivity];
    [self.failedStateBtn removeFromSuperview];
    
    //显示菊花
    [self addActivityViewBaseView:bgView];
    
    [[LZVideoCacheManager shareManager] checkVideoWithUrl:uu Completed:^(NSURL *completedUrl) {
        DLog(@"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^播放地址^^^===%@",completedUrl.absoluteString);
        
        [playerView updateURL:completedUrl];
        [playerView playAction];
        
        @weakify(self);
        [playerView setPlayEndBlock:^{//每次播放结束回调
            @strongify(self);
            [self playCountAddWithVideoId:videoId countAddBlock:playCountBlock];
        }];
        
        [playerView setLoadVideoFailBlock:^{
            @strongify(self);
            [self hiddenActivityView];
            [self showLoadFailBtnInBgView:bgView];
        }];
        
        //开始播放
        __weak LZCustomPlayerView *weakPlayer = playerView;
        playerView.videoCanbePlayBlock = ^(){//视频能够播放时,再进行add. 避免一开始的黑屏
            @strongify(self);
            [self hiddenActivityView];
            [self.failedStateBtn removeFromSuperview];

            __strong LZCustomPlayerView *strongPlayer = weakPlayer;
            if (strongPlayer.hidden == YES) {
                strongPlayer.hidden = NO;
            }
            [bgView addSubview:strongPlayer];
            [strongPlayer mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(0);
                make.trailing.mas_equalTo(0);
                make.leading.mas_equalTo(0);
                make.bottom.mas_equalTo(0);
            }];
            strongPlayer.alpha = 0;
            [UIView animateWithDuration:0.3 animations:^{
                strongPlayer.alpha = 1;
            }];
            
        };
        
    }];

}

#pragma mark - 点击视频海报直接播放的方法
/**
 点击视频海报直接播放的方法
 
 @param cellIndexPath 相应海报所在的cell的indexpath
 @param playerView 播放View
 @return 返回当前正在播放的cell的indexpath
 */
- (NSIndexPath *)playVideoWhenClickVideoCoverImgWithIndexPath:(NSIndexPath *)cellIndexPath playerView:(LZCustomPlayerView *)playerView playCountAddBlock:(void(^)(NSInteger totleCount))playCountBlock
{
    [playerView stopAction];
    UIView *bgView = [self.playVideoManagerDelegate playVidewManagerGetPlayBackgroundViewWith:cellIndexPath];
    NSString *urlStr = [self.playVideoManagerDelegate playVideoManagerGetVideoUrlWith:cellIndexPath];
    NSString *videoId = [self.playVideoManagerDelegate playVideoManagerGetVideoIdWithIndexPath:cellIndexPath];
    [self playVideoWithBgView:bgView playerView:playerView videoURL:urlStr videoID:videoId playCountAddBlock:playCountBlock];
    
    return cellIndexPath;
}

#pragma mark - 播放完成后,累加播放次数
- (void)playCountAddWithVideoId:(NSString *)videoId countAddBlock:(void(^)(NSInteger))countBlock
{
    [LZVideoPresenter videoPlayNumAddWithVideoID:videoId ResultSuccess:^(NSInteger totleCount) {
        if (countBlock) {
            countBlock(totleCount);
        }
    } ResultFailed:^(NSString *remind) {
        
    }];
}


#pragma mark - 停止播放
/**
 停止播放

 @param playerView <#playerView description#>
 */
- (void)stopPlayWithPlayerView:(LZCustomPlayerView *)playerView
{
    if (playerView) {
        [playerView stopAction];
        
        [UIView animateWithDuration:0.3 animations:^{
            playerView.alpha = 0;
        } completion:^(BOOL finished) {
            [playerView removeFromSuperview];
        }];
        
    }
}


#pragma mark - 继续播放.当播放列表跳转至其他页面,返回后继续,获取视频源进行播放
/**
 继续播放.当播放列表跳转至其他页面,返回后继续,获取视频源进行播放

 @param cellIndexPath <#cellIndexPath description#>
 @param playerView <#playerView description#>
 @param playCountBlock <#playCountBlock description#>
 */
- (NSIndexPath *)goOnPlayWithCellIndexPath:(NSIndexPath *)cellIndexPath playerView:(LZCustomPlayerView *)playerView tableView:(UITableView *)tableView playCountAddBlock:(void (^)(NSInteger))playCountBlock
{
    
    CGFloat screenMidY = SCREEN_HEIGHT/2; //屏幕中线
    NSArray *arr = [tableView indexPathsForVisibleRows];
    for (int i = 0; i < arr.count; i ++) {
        
        NSIndexPath *p = arr[i];
        CGRect cellRectInTable = [tableView rectForRowAtIndexPath:p];
        CGRect cellRectInSupeVCView = [tableView convertRect:cellRectInTable toView:nil];
        
        CGFloat playViewOriginY = cellRectInSupeVCView.origin.y - kRefreshSpace;
        CGFloat playViewLastY   = playViewOriginY + cellRectInSupeVCView.size.height;
        
        if (playViewOriginY < screenMidY && playViewLastY > screenMidY) {
            return [self playVideoWhenClickVideoCoverImgWithIndexPath:p playerView:playerView playCountAddBlock:playCountBlock];
        }
    }
    
    return cellIndexPath;

}

#pragma mark - 显示菊花
- (void)addActivityViewBaseView:(UIView *)baseView
{
    [baseView addSubview:self.activityView];
    [baseView bringSubviewToFront:self.activityView];
    [self.activityView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(baseView);
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    
    [self.activityView startActivityForWaitSomeSecond:.5];
}

#pragma mark - 隐藏菊花
- (void)hiddenActivityView
{
    [self.activityView stopActivity];
}

#pragma mark - 加载失败.显示失败按钮
- (void)showLoadFailBtnInBgView:(UIView *)bgView
{
    [bgView addSubview:self.failedStateBtn];
    [self.failedStateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsMake(0, 10, 0, 10));
    }];
}

#pragma mark - 加载失败后 点击按钮方法
/**
 加载失败,提示,点击重新加载调用的方法
 */
- (void)reloadAgainBtnAction
{
    [self.failedStateBtn removeFromSuperview];
     [self playVideoWithBgView:self.bgViewTemp playerView:self.playerViewTemp videoURL:self.videoURLTemp videoID:self.videoIDTemp playCountAddBlock:self.PlayCountBlock];
}

#pragma mark - 初始化
- (LZVideoActivityView *)activityView
{
    if (!_activityView) {
        _activityView = [[NSBundle mainBundle] loadNibNamed:@"LZVideoActivityView" owner:self options:nil].lastObject;
    }
    
    return _activityView;
}


- (UIButton *)failedStateBtn
{
    if (!_failedStateBtn) {
        _failedStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _failedStateBtn.backgroundColor = [UIColor clearColor];
        [_failedStateBtn setTitle:LZLocalizedString(@"video_play_failed", nil) forState:UIControlStateNormal];
        [_failedStateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _failedStateBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_failedStateBtn addTarget:self action:@selector(reloadAgainBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _failedStateBtn;
}

@end
